package com.sangeng.aspect;

import com.alibaba.fastjson.JSON;
import com.sangeng.annotation.SysLogAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

//自定义打印系统日志切面类
@Component
@Aspect
@Slf4j
public class SysLogAspect {
    //定义切点
    @Pointcut("@annotation(com.sangeng.annotation.SysLogAnnotation)")
    public void pt(){}
    //定义增强功能的方法(环绕通知）
    @Around("pt()")
    public Object printSysLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //调用原始方法
        try {
            //调用之前执行
            handleBefore(joinPoint);
            Object proceed = joinPoint.proceed();
            //调用之后执行
            handleAfter(proceed);
        } finally {
            // 结束后换行
            log.info("=======End=======" + System.lineSeparator());
        }
        return null;
    }

    private void handleBefore(ProceedingJoinPoint joinPoint) {
        //获取request对象
        HttpServletRequest request =getRequest();
        //获取方法上的注解对象
        SysLogAnnotation annotation = getAnnotation(joinPoint);
        log.info("=======Start=======");
        // 打印请求 URL
        log.info("URL            : {}",request.getRequestURL());
        // 打印描述信息
        log.info("BusinessName   : {}",annotation.businessName());
        // 打印 Http method
        log.info("HTTP Method    : {}",request.getMethod() );
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}",joinPoint.getSignature().getDeclaringType(),
                ((MethodSignature) (joinPoint.getSignature())).getName());
        // 打印请求的 IP
        log.info("IP             : {}",request.getRemoteHost());
        // 打印请求入参
        log.info("Request Args   : {}", JSON.toJSONString(joinPoint.getArgs()));
    }
    private void handleAfter(Object proceed) {
        // 打印出参
        log.info("Response       : {}",JSON.toJSONString(proceed));
    }
    //获取请求对象
    public HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) (RequestContextHolder.getRequestAttributes());
        //获取request对象
        HttpServletRequest request = requestAttributes.getRequest();
        return request;
    }
    //获取方法上的注解对象
    public SysLogAnnotation getAnnotation(ProceedingJoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) (joinPoint.getSignature());
        SysLogAnnotation sysLogAnnotation = signature.getMethod().getAnnotation(SysLogAnnotation.class);
        return sysLogAnnotation;
    }

}
